package org.dkakunsi.aplikasitoko.data.adapter;

import java.util.List;

import org.dkakunsi.aplikasitoko.data.access.BarangDataAccess;
import org.dkakunsi.aplikasitoko.data.entity.Barang;
import org.dkakunsi.aplikasitoko.data.util.ApplicationDataException;
import org.dkakunsi.aplikasitoko.data.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class BarangDataAdapter implements BarangDataAccess {

	private Session session;
	private Transaction tx;
	
	public BarangDataAdapter() {
		this.session = HibernateUtil.openSession();
		this.tx = session.beginTransaction();
	}
	
	public BarangDataAdapter(Session session) {
		this.session = session;
		this.tx = session.beginTransaction();
	}

	@Override
	public void save(Object object) throws ApplicationDataException {
		Barang brg = null;
		
		try {
			brg = (Barang) object;
			
			session.save(brg);
			tx.commit();
		} catch(ConstraintViolationException x) {
			throw new ApplicationDataException("Duplikasi data untuk KODE : " + brg.getKode());
		}
	}

	@Override
	public void update(Object object) throws Exception {
		Barang brg = (Barang) object;
		
		session.merge(brg);
		tx.commit();
	}

	@Override
	public void delete(Object object) throws Exception {
		Barang brg = (Barang) object;
		
		session.delete(brg);
		tx.commit();
	}

	@Override
	public Object getByID(String id) throws ApplicationDataException {
		Barang brg = (Barang) session.get(Barang.class, id);
		tx.commit();

		if(brg != null){
			return brg;
		} else {
			throw new ApplicationDataException("Kesalahan KODE");
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Object getBy( String nama ) throws Exception {
		List<Barang> brg = null;
		
		brg = session.createQuery("from Barang where nama = :namaBarang").setParameter("namaBarang", nama).list();

		return brg.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Barang> getAll() throws Exception {
		List<Barang> all = null;
		
//		session = HibernateUtil.openSession();
		all = session.createQuery("from Barang order by KODE").list();
//		session.close();

		return all;
	}
	
	@Override
	public Session getSession() {
		return this.session;
	}
}
